package connectioncount

import (
	"gomonitor-server/src/db"
	"gomonitor-server/src/dto"
	"gomonitor-server/src/mylog"
	"net"
	"time"
)

var connectionInfoMap = make(map[net.Conn]*dto.ConnectionInfo)

func GetConnectionCount() int {
	return len(connectionInfoMap)
}

func AddConnection(conn net.Conn) {
	connectionInfoMap[conn] = &dto.ConnectionInfo{Conn: conn, StartTime: time.Now()}
	connCount := GetConnectionCount()
	mylog.Logger.Infof("当前连接数:%d", connCount)
}
func UpdateSysInfo(conn net.Conn, sysInfo dto.SysInfo) {
	info, exsit := connectionInfoMap[conn]
	if exsit {
		if info.LastSysInfo == nil {
			info.LastSysInfo = &sysInfo
			db.HostStateOnline(info)
		}
	}
}
func DisConnection(conn net.Conn) {
	connectionInfo, exsit := connectionInfoMap[conn]
	if exsit {
		connectionInfo.EndTime = time.Now()
		sysInfo := connectionInfo.LastSysInfo
		var ip string
		if sysInfo != nil {
			if len(sysInfo.NetInfo) > 0 {
				ip = sysInfo.NetInfo[0].Ip
			} else {
				ip = ""
			}
		}
		db.HostStateOffline(connectionInfo)
		delete(connectionInfoMap, conn)
		mylog.Logger.Infof("客户端ip:%s,断开后连接数:%d", ip, GetConnectionCount())
	}
}
